package com.ztom.top100;

import java.util.HashMap;
import java.util.Map;

/**
 * 只出现一次的数字
 * <p>
 * https://leetcode-cn.com/problems/single-number/
 *
 * @author ZhangTao
 */
public class Code48SingleNumber {

    /**
     * 计数法
     *
     * @param nums
     * @return
     */
    public int singleNumber1(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.remove(num);
            } else {
                map.put(num, 1);
            }
        }
        return map.keySet().iterator().next();
    }

    /**
     * 位运算
     * a ^ a = 0
     * a ^ 0 = a
     *
     * @param nums
     * @return
     */
    public int singleNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        int a = 0;
        for (int num : nums) {
            a ^= num;
        }
        return a;
    }
}
